import {Component} from '@angular/core';
import {ApesField} from './apes-field';
import {
  backField,
  deepClone, fillField,
  getO,
  missing,
  replaceAll
} from '../../../../utils/utils';
import {ApiService} from '@core/services/http/api.service';
import {Events} from '@core/services/events/Events';
import {ExpressionService} from '@core/services/expression/ExpressionService';
import {SubjectService} from '@core/services/events/subject.service';
import { Subject } from 'rxjs/internal/Subject';
import { catchError, debounceTime, distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
import { SearchService } from '@core/services/search.service';

@Component({
  selector: 'formly-field-select',
  template: `
    <div apes-row>
      <div apes-col apesMd="24">
        <ng-select [items]="itemsData"
                   bindLabel="name"
                   [hideSelected]="true"
                   [optionWidth]="width"
                   [disabled]="to.disabled"
                   [placeholder]="to.placeholder"
                   [multiple]="multiple"
                   [formlyAttributes]="field"
                   [formControl]="formControl"
                   [virtualScroll]="true"
                   [loading]="contractLoading"
                   [typeahead]="contractinput$"
                   [searchBtn]="_searchBtn"
                   [searchable]="_ShowSearch"
                   (searchBtnFn)="onSearch()"
                   (change)="backData()"
                   (scrollToEnd)="fetchMore()"
                   class="select-business">
          <!-- 表头部分 -->
          <ng-template ng-label-tmp let-item="item" let-clear="clear">
            <span class="ng-value-label">{{formatter(item, getValueFormatter())}}</span>
            <span class="ng-value-icon right" (click)="clear(item)" aria-hidden="true">×</span>
          </ng-template>
          <ng-template ng-option-tmp let-item="item">
            <span class="ng-value-label">{{formatter(item, getDownFormatter())}}</span>
          </ng-template>

        </ng-select>
      </div>
    </div>


  `
})
export class FormlyFieldSelectBusiness extends ApesField {
  apesConfig: any;
  searchFormId: string;
  searchSelectApi: string;
  _ShowSearch = true;
  _searchBtn = false;
  private _current = 0;
  multiple = false;
  width = 0;
  private _pages = 0;
  private _searchText = '';
  contractLoading = false;
  itemsData: any;
  contractinput$ = new Subject<string>();
  private _domain;
  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService,
              protected subject: SubjectService, protected searchService: SearchService) {
    super(apiService, events, expressionService, subject);
    this.loadContract();
  }

  ngOnInit() {
    this.apesConfig = this.extend(this.to);
    this.width = this.to.width;
    this.searchFormId = this.to.searchFormId;
    this.searchSelectApi = this.to.api;
    this.multiple = this.to.multiple === 'true' || false;
    if (this.to['domain']) {
      this.to.domain = replaceAll(this.to.domain, '\'', '');
      this._domain = JSON.parse(this.to.domain);
    }
    if (this.to['searchFormId']){
      this._searchBtn = true;
    }
    // 设置下拉选项
    if (this.to['items']) {
      this.itemsData = getO(this.to['items']);
      this._ShowSearch = false;
    }

  }
  ngAfterViewInit() {
    // 增加 init xml 选项，表示不搜索下拉， 默认查询api作为下拉选项
    if (this.apesConfig['init'] && this.apesConfig['api']) {
      this.getItemData();
      // this._ShowSearch = false;
    }
    if (this._ShowSearch) {
      this.loadContract();
    }
  }
  protected extend(data: any) {
    const result = {};
    for (const key in data) {
      const value = data[key];
      result[key] = value;
    }
    return result;
  }
  backData() {
    const context = this.to.context || {};
    backField(this, context);
  }


  private loadContract() {
    this.contractinput$.pipe(
      debounceTime(500),
      distinctUntilChanged(),
      tap(() => this.contractLoading = true),
      switchMap((term) => {
        if (missing(term)) {
          this.contractLoading = false;
          return of([]);
        }
        if ( this._searchText === term) return of([]);
        this._current = 0;
        this._searchText = term;
        const data = this.getApiParams();
        return this.apiService.post(this.searchSelectApi, data).pipe(
          map((res) => {
              this.itemsData = [];
              this._searchText = term;
              this.itemsData = this.itemsData.concat(res.content);
              this._current = res.page + 1;
              this._pages = res.pages;
              return res.content;
            }
          ),
          catchError(() => of([])), // empty list on error
          tap(() => this.contractLoading = false)
        ); })
    ).subscribe();
  }


  fetchMore() {
    this.contractLoading = true;
    // using timeout here to simulate backend API delay
    if (this._current === this._pages || this._searchText === '') {
      this.contractLoading = false;
      return;
    }
    this.getItemData();
  }
  getItemData() {
    const data = this.getApiParams();
    this.apiService.post(this.searchSelectApi, data).subscribe(item => {
      this.contractLoading = false;
      if (item.page === 0) {
        this.itemsData = [];
      }
      this.itemsData = this.itemsData.concat(item.content);
      this._current = item.page + 1;
      this._pages = item.pages;
    });
  }

  /*
  * 弹窗事件
  * */
  onSearch() {
    const key = this.to.componentRef.field.key;
    const options = {multiple: this.multiple}; // 声明查询条件
    if (this._domain) {
      const group = fillField(this._domain,this.formState,true,this._searchText);
      console.log(JSON.stringify(group));
      if ( !(group.filters.length === 0 && group.groups.length === 0 )) {
        options['domain'] = group   ;
      }
    }
    // 弹窗api与下拉api保持一致
    options["api"] = this.searchSelectApi;
    this.searchService.openDialog(this.searchFormId, options, (result: any) => {
      if (result && result.length > 0) {
        this.itemsData = [];
        for (let i = 0, len = result.length; i < len; i++ ) {
          this.itemsData = this.itemsData.concat(result[i]);
        }
        if (this.multiple) {
          if (this.model[key] !== null && this.model[key] !== undefined) {
            const items = deepClone(this.model[key]);
            this.itemsData = items.concat(this.itemsData);
          }
          this.form.get(key).patchValue(this.itemsData);
        } else {
          this.form.get(key).patchValue(this.itemsData[0]);
        }

      }
    }).subscribe();
  }

  getValueFormatter(): string {
    return this.to.valueFormatter || 'value.name';
  }
  getDownFormatter(): string {
    return this.to.downFormatter || '\'[ \' + value.id + \' ]\' + \' \' + value.name';
  }
  getApiParams() {
    const data = {key: this._searchText, page: this._current, size: 20};
    if (this._domain) {
      const group =  fillField(this._domain,this.formState,false,this._searchText);
      data['group'] = group;
    }
    return data;
  }


  formatter(value: any, expression: string) {
    return this.expressionService.evaluate(expression, {
      context: this.formState,
      model: this.formState.model,
      value: value
    });
  }

}
